//
//  WJMineViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/18.
//

import UIKit
import SnapKit
import StoreKit

class WJMineViewController: WJBaseViewViewController {

    /// 表格单元格类型
    enum CellType {
        case support
        case rateUs
        case privacyPolicy
        case eula
        case mySign
        
        var title: String {
            switch self {
            case .support:
                return "Support"
            case .rateUs:
                return "Rate Us"
            case .privacyPolicy:
                return "Privacy Policy"
            case .eula:
                return "EULA"
            case .mySign:
                return "My Sign"
            }
        }
        
        var imageName: String {
            switch self {
            case .support:
                return "Icon_line_repair"
            case .rateUs:
                return "Icon_line_rate us"
            case .privacyPolicy:
                return "Icon_line_fttp"
            case .eula:
                return "Icon_line_eula"
            case .mySign:
                return "Icon_line_sign"
            }
        }
    }
    
    /// 功能区单元格数据
    private let functionCellTypes: [CellType] = [
        .support,
        .rateUs,
        .privacyPolicy,
        .eula,
        .mySign
    ]
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.register(WJMineOperationCell.self, forCellReuseIdentifier: "WJMineOperationCell")
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 72
        tableView.backgroundColor = UIColor(hex: "#FFFFFF")
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))
        tableView.sectionHeaderHeight = CGFloat.leastNonzeroMagnitude
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.layer.cornerRadius = 16.0
        tableView.layer.masksToBounds = true
        tableView.isScrollEnabled = false
        return tableView
    }()
    
    // 页面标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.font = UIFont.montserratSemiBold(24)
        label.text = "Mine"
        label.textColor = UIColor(hex: "#121212")
        return label
    }()
    
    lazy var cardImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFit
        imgView.image = UIImage(named: "open_vip")
        imgView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(goToPurchase(_:)))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    lazy var restoreButton: WJMineOperationButton = {
        let button = WJMineOperationButton(title: "Restore Purchases", imageName: "Icon_line_refresh")
        button.addTarget(self, action: #selector(restorePurchase(_:)), for: .touchUpInside)
        return button
    }()
    
    lazy var tbBgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#121212", alpha: 0.05)
        view.layer.cornerRadius = 24
        view.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        view.layer.borderWidth  = 0.5
        view.layer.shadowColor = UIColor.white.cgColor
        view.layer.shadowOffset = CGSize(width: 0, height: 0)
        view.layer.shadowOpacity = 0.7
        view.layer.shadowRadius = 3.0
        view.layer.masksToBounds = false
        
        return view
    }()
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        isHiddenCustomTabBar = false
        setupUI()
        setupConstraints()
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI(_:)), name: .purchaseSucessNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI(_:)), name: .purchaseRestoredNotification, object: nil)
        
        if WJUserManager.shared.isVIP {
            cardImgView.isHidden = true
            updateConstraints()
        }
    }
    
    // MARK: - Setup
    private func setupUI() {
        view.addSubview(titleLabel)
        view.addSubview(cardImgView)
        view.addSubview(restoreButton)
        view.addSubview(tbBgView)
        tbBgView.addSubview(tableView)
    }
    
    private func setupConstraints() {
        // 标题约束
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(-32)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(32)
        }

        if let vipImage = cardImgView.image,
           vipImage.size.height > 0,
           vipImage.size.width > 0 {
            let aspectRate = vipImage.size.width / vipImage.size.height
            let margin = 16.0
            let width = kScreenWidth - margin * 2.0
            let height = width / aspectRate
            
            cardImgView.snp.makeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(10)
                make.leading.trailing.equalToSuperview().inset(16)
                make.height.equalTo(height)
            }
        } else {
            cardImgView.snp.makeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(10)
                make.leading.trailing.equalToSuperview().inset(16)
                make.height.equalTo(79)
            }
        }
        
        restoreButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalTo(cardImgView.snp.bottom).offset(24)
            make.height.equalTo(56)
        }
        
        // 表格约束
        tbBgView.snp.makeConstraints { make in
            make.top.equalTo(restoreButton.snp.bottom).offset(24)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(320)
        }
        
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(12)
        }
    }
    
    func updateConstraints() {
        cardImgView.snp.makeConstraints { make in
            make.height.equalTo(0)
        }
    }
    
    func pushToWebView(_ urlStr: String) {
        let vc = WJWebViewController()
        vc.urlString = urlStr
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func openEmailComposer(_ email: String) {
        let urlstr = "mailto:\(email)?body=PDF Sign:"
        let mailtoUrlString = urlstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        
        if let url = URL(string: mailtoUrlString) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    @objc func restorePurchase(_ sender: UIButton) {
        WJProgressHUD.showLoading()
        WJPurchaseManager.shared.restorePurchases()
        WJPurchaseManager.shared.delegate = self
    }
    
    @objc func goToPurchase(_ tap: UITapGestureRecognizer) {
        let vc = RemoteConfigValues.getCurrentPurchaseVC()
        let nav = WJNavigationController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true)
    }
    
    @objc func updateUI(_ notif: NSNotification) {
        cardImgView.isHidden = true
        updateConstraints()
    }
}

// MARK: - UITableViewDataSource & Delegate

extension WJMineViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return functionCellTypes.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellType = functionCellTypes[indexPath.row]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "WJMineOperationCell", for: indexPath) as? WJMineOperationCell else {
            return WJMineOperationCell()
        }
        
        if indexPath.row != 4 {
            cell.selectionStyle = .blue
        } else {
            cell.selectionStyle = .none
        }
        
        // 配置分割线显示状态
        let isLastCell = indexPath.row == functionCellTypes.count - 1
        cell.configure(with: cellType.title, icon: UIImage(named: cellType.imageName), isLastCell: isLastCell)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let cellType = functionCellTypes[indexPath.row]
        switch cellType {
        case .support:
//            print("Support button tapped")
            openEmailComposer("17209605137@163.com")
        case .rateUs:
            if let windowScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
                SKStoreReviewController.requestReview(in: windowScene)
            }
        case .privacyPolicy:
            let urlStr = "https://www.freeprivacypolicy.com/live/b4baff6e-61f8-491e-b138-b13696060fd3"
            pushToWebView(urlStr)
        case .eula:
            let urlStr = "https://www.freeprivacypolicy.com/live/f2a037ca-a61e-4802-a0b5-8e5785c44762"
            pushToWebView(urlStr)
        case .mySign:
            let vc = WJMySigntruesViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    // 设置组间距
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }
}

extension WJMineViewController: WJPurchaseManagerDelegate {
    func productsLoaded(products: [SKProduct]) {
        
    }
    
    func purchaseCompleted(result: WJPurchaseResult) {
       
        switch result {
        case .success(let receipt):
            print("购买成功，收据: \(receipt)")
            WJProgressHUD.showInfo(with: "Purchase successful")
           dismiss(animated: true)
            
        case .failure(let error):
            print("购买失败: \(error)")
            WJProgressHUD.showInfo(with: error)
            
        case .cancelled:
            print("用户取消购买")
            WJProgressHUD.showInfo(with: "Purchase Canceled")
            
        case .restored:
            print("恢复购买成功")
            WJProgressHUD.showInfo(with: "Restore successful")
        case .restoreFailure(let error):
            WJProgressHUD.showInfo(with: error)
        }
    }
    
    func productsRequestFailed(error: String) {
        print("获取产品失败: \(error)")
    }
}

